let net = require("net");
let server = net.createServer();
let fs = require("fs");

function parserHeader(h) {
  let obj = {};
  let headers = h.split(/\r\n/);
  let line = headers.shift();
  let [method, path, version] = line.split(" ");
  let head = {};
  headers.forEach((line) => {
    let [key, value] = line.split(": ");
    head[key] = value;
  });
  obj["method"] = method;
  obj["path"] = path;
  obj["version"] = version;
  obj["headers"] = head;
  return obj;
}
let {
  Readable
} = require("stream");
class IncomingMessage extends Readable {
  _read() {}
}

function parser(socket, callback) {
  let im = new IncomingMessage();
  let flag = true;
  let length = 0;
  let cLength = 0;
 
  function fn() {
    let data;
    while ((data = this.read())) {
      // console.log(data.toString(),222)
      if (!flag) {
        // console.log(data.toString())
        // im.push(content);
      }else{
        flag = false;
        let result = data.toString();
        // console.log(JSON.stringify(result),'----\r\n')
        let [head, ...content] = result.split(/\r\n\r\n/);
        let obj = parserHeader(head); // 解析header
        length = obj.headers['Content-Length'];
        // console.log(obj)
        Object.assign(im, obj);
        // readable方法会触发多次，触发一次后就移除掉
        socket.removeListener("readable", fn);
        callback(im, socket);
        DataStrem();
        // console.log(content.join(/\r\n\r\n/))
        socket.unshift(content.join('\r\n\r\n'));
      }
      
    }
    // im.push(null)
  }
  socket.on("readable", fn); // 缓冲区里面有数据
  // DataStrem()

  function DataStrem() {
    //  console.log(length)
    if (!length){
      im.emit('end');
      return ;
    }
    length = Number(length)
    // console.log(length)
    socket.on("data", (chunk) => {
      cLength += chunk.length;
      // console.log(chunk.length, cLength)
      if (cLength > length){
          im.emit('data', chunk)
          im.emit('end')
      }else{
        im.emit('data', chunk)
      }
    });
  }
}
server.on("connection", function (socket) {
  // console.log('1')
  parser(socket, function (req, res) {
    // console.log(3)
    server.emit("request", req, res);
  });
});
server.on("request", function (req, res) {
  // console.log(4)
  // console.log(req.method, req.path);
  // console.log(req.headers);
  const { StringDecoder } = require('string_decoder');
  var decoder = new StringDecoder('utf8')
  req.on("data", function (data) {
    // 需要用状态机来处理
    // console.log(decoder.write(data).toString()+ '\r\n\r\n???');
    // console.log('??');
  });

  req.on("end", function () {
    // console.log(req.path,'path')
    if (req.path == "/") {
      var rows = [];
      rows.push(`HTTP/1.1 200 OK`);
      // text - plain
      rows.push(`Content-Type: text/html; charset=utf-8`);
      rows.push(`Date: ${new Date().toGMTString()}`);
      rows.push(`Connection: keep-alive`);
      rows.push(`Transfer-Encoding: chunked`);
      // let responseBody = `ok完毕`;
      // rows.push(`\r\n${Buffer.byteLength(responseBody).toString(16)}\r\n${responseBody}\r\n0\r\n\r\n`);

      let responseBody = `${fs.readFileSync("./static/upload.html", "utf8")}`;
      rows.push(
        `\r\n${Buffer.byteLength(responseBody).toString(
          16
        )}\r\n${responseBody}\r\n0\r\n\r\n`
      );

      let response = rows.join("\r\n");
      res.write(Buffer.from(response));
      res.end();
    } else {
      var rows = [];
      rows.push(`HTTP/1.1 200 OK`);
      rows.push(`Content-Type: text/html; charset=utf-8`);
      rows.push(`Date: ${new Date().toGMTString()}`);
      let response = rows.join("\r\n");
      res.write(Buffer.from(response));
      res.end();
    }
  });
});
server.listen(5555);